//
//  YTWebViewController.m
//  YiTuUserClient
//
//  Created by 石少庸 on 2017/2/17.
//  Copyright © 2017年 YiTu. All rights reserved.
//

#import "YTWebViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface YTWebViewController ()<WKUIDelegate, WKNavigationDelegate, UIGestureRecognizerDelegate>

@property (strong, nonatomic) WKWebView *webView;

@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation YTWebViewController

#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createWebView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)dealloc {
    [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))];
    [YTNetManager networkActivityIndicatorDissmis];
}

#pragma mark - 初始化

/// 创建webview
- (void)createWebView {
    // 配置
    if (_naviTitle) {
        self.navigationItem.title = _naviTitle;
    }
    WKWebViewConfiguration *webViewConfig = [[WKWebViewConfiguration alloc] init];
    webViewConfig.allowsInlineMediaPlayback = true;
    
    // 初始化
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)
                                  configuration:webViewConfig];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    _webView.allowsBackForwardNavigationGestures = true;
    _webView.scrollView.scrollEnabled = true;
    _webView.backgroundColor = [UIColor whiteColor];
    [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                  options:NSKeyValueObservingOptionNew
                  context:WkwebBrowserContext];
    [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(title))
                  options:NSKeyValueObservingOptionNew
                  context:WkwebBrowserContext];
    [self.view addSubview:_webView];
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [NSURLCache sharedURLCache].diskCapacity = 0;
    [NSURLCache sharedURLCache].memoryCapacity = 0;
    
    // 进度条
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 2)];
    _progressView.progressViewStyle = UIProgressViewStyleBar;
    _progressView.progressTintColor = kMainBlueColor;
    _progressView.hidden = true;
    [self.view addSubview:_progressView];
    
    // 加载网络
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]]];
    
    [self createBarItems:NO];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [YTNetManager networkActivityIndicatorDissmis];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    _progressView.hidden = NO;
    if (![YTNetManager isReachableNetwork]) { //没网
        @weakify(self);
        [self loseConnectionRefreshAction:^{
            @strongify(self);
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlString]]];
        }];
    } else {
        [YTNetManager networkActivityIndicatorShow];
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [YTNetManager networkActivityIndicatorDissmis];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == _webView) {
        [_progressView setAlpha:1.0f];
        BOOL animated = _webView.estimatedProgress > _progressView.progress;
        [_progressView setProgress:_webView.estimatedProgress animated:animated];
        
        if(_webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [_progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [_progressView setProgress:0.0f animated:NO];
            }];
        }
    } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(title))] && object == _webView) {
        if (_naviTitle) {
            self.navigationItem.title = _naviTitle;
            return;
        }
        self.navigationItem.title =  _webView.title;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - webview navi

/// 关闭
- (void)closeWebviewAction {
    [self.navigationController popViewControllerAnimated:true];
}

/// 返回上一层
- (void)backWebviewAction {
    if ([_webView canGoBack]) {
        [_webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/** 创建左边items*/
- (void)createBarItems:(BOOL)isClose {
    UIBarButtonItem *firstItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"public_back_black"] style:UIBarButtonItemStyleDone target:self action:@selector(backWebviewAction)];
    
    if (!isClose) {
        self.navigationItem.leftBarButtonItem = firstItem;
        return;
    }
    UIBarButtonItem *secondItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeWebviewAction)];
    [secondItem setTintColor:kMainBlueColor];
    self.navigationItem.leftBarButtonItems = @[firstItem, secondItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
